<?php
//error_reporting(E_ALL);
//require_once('config.php');
require_once('idna_convert.class.php');

function create_vhost($domain,$ip)
{
	include('config.php');
	echo "<p><b>CREATING CONFIGURATION FOR DOMAIN $domain</p></b>";
	echo '<p>Checking ip address: ';
	$ip_isset=false;																					//	IP Available test Section
	$local_ip_list=shell_exec("$ip_bin a | grep 'inet ' | awk '{ print $2 }' | cut -f1 -d'/' ");
	if ($ip == '*') $ip_isset=true;
	foreach(preg_split("/(\r?\n)/", $local_ip_list) as $line)
	{
		if ($ip == $line) $ip_isset=true;
	}
	if (!$ip_isset) 																					//	Break if ip address unavailable
	{
		echo "FALSE</p>";
		return 'Unavailable IP address';
		break;
	}
	echo "OK</p>";
																										//	Vhost Available Test
	echo "<p>Checking current VirtualHost's: ";
	$vhost_free=false;
	$grep_domain=shell_exec("$apache2ctl_bin -S 2>/dev/null | grep ' $domain'");
	echo $grep_domain;
	if ($grep_domain != '')
	{
		echo "FALSE</p>";
		return "VirtualHost already exists:\n$grep_domain";
		break;																							// Break if VirtualHost already exists
	}
	echo "OK</p>";
																										//	All checks passed, creating VHost
	echo "<p>Creating DocumentsRoot directory: ";
	$docroot=$htdocs_root.$domain.'/httpd';
	echo shell_exec("mkdir -p $htdocs_root$domain/httpd 2>&1");
	echo " OK</p>";
	echo "<p>Building VHost config file: ";																//	Building VHost config file
	$default_vhost = preg_replace('/\[domain\]/',$domain,$default_vhost);
	$default_vhost = preg_replace('/\[ip\]/',$ip,$default_vhost);
	$default_vhost = preg_replace('/\[docroot\]/',$docroot,$default_vhost);
	//echo $default_vhost;
	echo shell_exec("echo '$default_vhost' > $apache_vhost_config_dir$domain 2>&1");
	//echo shell_exec("sudo $apache_init restart 2>&1");
	echo "OK</p>";
		
	return true;																						//	All done function returns true
}

function create_ftp($domain,$username,$password)
{
	include('config.php');
	$domain=addslashes($domain);
	$username=addslashes($username);
	//$password=addslashes($password);
	echo "<p>Creating FTP user $username echo $password: ";
	$result = shell_exec("sudo $pure_pw_bin list | grep '$username' | awk '{ print \$1 }'");								//	Getting users list
//	if ($result != "")																					//	If user exists - reconfiguring it
//	{
//		echo "User exists! reconfiguring user $username: ";
//		shell_exec("sudo $pure_pw_bin usermod $username -u $pure_pw_uid -g $pure_pw_gid -d $htdocs_root$domain");
//		shell_exec("( echo \"$password\"; echo \"$password\" ) | sudo $pure_pw_bin passwd $username");
//		shell_exec("sudo $pure_pw_bin mkdb");
//		echo "OK</p>";
//	} else																								// If new user - creating it
//	{
		shell_exec("( echo \"$password\"; echo \"$password\" ) | sudo $pure_pw_bin useradd $username -u $pure_pw_uid -g $pure_pw_gid -d $htdocs_root$domain");
		shell_exec("sudo $pure_pw_bin mkdb");
		echo "OK</p>";
//	}
	
return true;	
}

function create_db($username,$password,$database)
{
	$username=addslashes($username);
	$password=addslashes($password);
	$database=addslashes($database);
	include ('config.php');
	echo "<p>Creating MySQL Database '$database' and User '$username' Pass '$password':";
	$mysql_connect=mysql_connect($mysql_host,$mysql_user,$mysql_pass);
	if (!$mysql_connect)
	{
		return mysql_error();
		break;
	}
	
	$query="SELECT user from mysql.user WHERE user='$username'";
	$result=mysql_query($query);
	while($row = mysql_fetch_array($result)) if ($row['user'] != '')									//	Checking if User already exists if yes - break
	{
		return "MySQL user $username already exists, break\n";
		break;
	}
	
	$query="select db from mysql.db where db='$database';";
	$result=mysql_query($query);
	while($row = mysql_fetch_array($result)) if ($row['db'] != '')										//	Checking if Database already exists if yes - break
	{
		return "MySQL DataBase '$database' already exists, break\n";
		break;
	}
	
	mysql_query("CREATE database $database");															//	Creating Database
	mysql_query("GRANT ALL PRIVILEGES ON $database.* TO $username@'localhost' IDENTIFIED BY '$password';") or die (mysql_error());	//	Creating User
	mysql_query("FLUSH PRIVILEGES;");
	echo "OK</p>";
	
	
	mysql_close($mysql_connect);
	return true;
}

function create_with_wp($domain, $wp_type, $db_name, $db_user, $db_pass)
{
	include ('config.php');
	$src_dir=$wp_templates_dir.$wp_type.'/httpd';
	$dst_dir=$htdocs_root.$domain.'/';
	echo "SRC: $src_dir";
	echo "DST: $dst_dir";
	shell_exec("mv $dst_dir/httpd $dst_dir/httpd_old");
	shell_exec("cp -R $src_dir $dst_dir");
	$file_pwd="$dst_dir"."httpd/wp-config.php";
	echo $file_pwd;
	$file = fopen($file_pwd, 'r');
	$text = fread($file, filesize($file_pwd));
	fclose($file);
	$text = str_replace('db-sname', $db_name, $text);
	$text = str_replace('db-suser', $db_user, $text);
	$text = str_replace('db-spass', $db_pass, $text);
	
	
	$file = fopen($file_pwd, 'w');
	fwrite($file, $text);
	fclose($file);
	
}


require_once('config.php');

//echo create_vhost("sath.pp.uaa","127.0.0.1",false);
//echo create_ftp('sath.pp.uaa','sath','max');
//echo create_db('sath','sath_password','sath_db');

?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<a href="?manage">Manage Domains</a>
<title>Web Hosting Script</title>

<form action="?go" method="post">
<br>Domain:<input type="text" name="domain" />
<br>IP:<select name="ip">
<br>
<!-- <option selected value="*">*(all)</option> -->
<?
include ('config.php');
$local_ip_list=shell_exec("$ip_bin a | grep 'inet ' | awk '{ print $2 }' | cut -f1 -d'/' ");
foreach(preg_split("/(\r?\n)/", $local_ip_list) as $line) echo "<option value=\"$line\">$line</option>\n";
?>
</select>
<br>FTP Username:<input type="text" name="ftp_user" />
<br>FTP Password:<input type="text" name="ftp_pass" />
<br>DB Name:<input type="text" name="db_name" />
<br>DB User:<input type="text" name="db_user" />
<br>DB Pass:<input type="text" name="db_pass" />
<br><input type="checkbox" name="wp_type" value="wp_heb">WordPress HEB</input>
<br><input type="checkbox" name="wp_type" value="wp_ca">WordPress CA</input>
<br><input type="submit" name="Submit" />
</form>
<?
$_POST['domain'] = str_replace(' ','',$_POST['domain']);
if (isset ($_GET['go'])&&$_POST['domain']!=''&&$_POST['ip']!=''&&$_POST['ftp_user']!=''&&$_POST['ftp_pass']!=''&&$_POST['db_name']!=''&&$_POST['db_user']!=''&&$_POST['db_pass']!='')
{
		$domain=$_POST['domain'];
		$ip=$_POST['ip'];
		$ftp_user=$_POST['ftp_user'];
		$ftp_pass=$_POST['ftp_pass'];
		$db_name=$_POST['db_name'];
		$db_user=$_POST['db_user'];
		$db_pass=$_POST['db_pass'];
		echo '<p>';
		$return = create_vhost($_POST['domain'],$_POST['ip']);
		if (isset($_POST['wp_type']) && $_POST['wp_type'] != '')
		create_with_wp($_POST['domain'], $_POST['wp_type'], $_POST['db_name'], $_POST['db_user'],$_POST['db_pass']);
		if ($return == 1)
		$return = create_ftp($_POST['domain'],$_POST['ftp_user'],$_POST['ftp_pass']);
		if ($return == 1)
		$return = create_db($_POST['db_user'],$_POST['db_pass'],$_POST['db_name']);
		if ($return != 1) echo '<p style="color:#FF0000"><b>'.$return.'</b></p>'; else
		echo "<p style=\"color:#00FF00\"><b>Configuration for $domain successfully created</b></p>";
		echo shell_exec("sudo $apache_init reload 2>&1");
		echo "OK";
		echo "<p>Writing Log: ";
		$mysql_connect=mysql_connect($mysql_host,$mysql_user,$mysql_pass);
		if (!$mysql_connect)
		{
		return mysql_error();
		break;
		}
		$ftp_dir="$htdocs_root$domain/";
		$query="INSERT INTO  `webhostscript`.`vhosts` (
`id` ,
`domain` ,
`ip` ,
`ftp_user` ,
`ftp_pass` ,
`ftp_dir` ,
`db_name` ,
`db_user` ,
`db_pass`
)
VALUES (
NULL ,  '$domain',  '$ip',  '$ftp_user',  '$ftp_pass', '$ftp_dir',  '$db_name',  '$db_user',  '$db_pass'
);";
		mysql_query($query);
		mysql_close($mysql_connect);
		echo 'OK</p>';
}

if (isset($_GET['manage']))
{
	$mysql_connect=mysql_connect($mysql_host,$mysql_user,$mysql_pass);
	if (!$mysql_connect)
	{
		return mysql_error();
		break;
	}
	if ($_GET['manage']=='delete'&&isset($_POST['id']))
	{
		$id=$_POST['id'];
		$result=mysql_query("SELECT domain,ftp_user,db_name,db_user FROM `webhostscript`.`vhosts` WHERE id='$id' ORDER BY id;");
		while($row = mysql_fetch_array($result))
		{
			$drop_db=$row['db_name'];
			mysql_query("DROP DATABASE $drop_db;");
			$drop_user=$row['db_user'];
			mysql_query("DROP USER $drop_user@localhost;");
			mysql_query("DELETE FROM `webhostscript`.`vhosts` WHERE id='$id';");
			$drop_ftp=$row['ftp_user'];
			shell_exec("sudo $pure_pw_bin userdel $drop_ftp");
			$drop_domain=$row['domain'];
			shell_exec("rm -f /etc/apache2/sites-generated/$drop_domain");
			echo "<p><br>Deleted Domain: $drop_domain;<br>Deleted Database: $drop_db; <br>Deleted Database user: $drop_user; <br>Deleted FTP: $drop_ftp</p>";
			
		}
		
		
	}
	$result=mysql_query("SELECT * FROM `webhostscript`.`vhosts`");
	//echo '<form action="?manage=delete" method="post">';
	echo '<table border="1">';
	//echo '<tr><td>Domain:</td><td>Bind IP:</td><td>FTP user:</td><td>FTP pass:</td><td>DB name:</td><td>DB user:</td><td>DB pass:</td><td>Delete?</td><td></td></tr>'."\n";
	echo '<tr><td>Domain:</td><td>Bind IP:</td><td></td><td>Delete?</td></tr>'."\n";
	while($row = mysql_fetch_array($result))
		{
		$punycode=$row['domain'];
		$idn = new idna_convert(array('idn_version'=>2008));
		//$punycode=(stripos($punycode, 'xn--')!==false) ? $idn->decode($punycode) : $idn->encode($punycode);
		$punycode=(stripos($punycode, 'xn--')!==false) ? $idn->decode($punycode) : $punycode='';
	//	echo "<tr><td>".$row['domain']."</td><td>".$row['ip']."</td><td>".$row['ftp_user']."</td><td>".$row['ftp_pass']."</td><td>".$row['db_name']."</td><td>".$row['db_user']."</td><td>".$row['db_pass']."</td><td align='right'>FTP_USER: ".$row['ftp_user']."<br>DB_USER: ".$row['db_user']."<br> DB_NAME: ".$row['db_name']."<br> DB_PASS: ".$row['db_pass']."<br>FTP_PASS: ".$row['ftp_pass']."<br></td><td><form action=\"?manage=delete\" method=\"post\"><input type=\"hidden\" name=\"id\" value=\"".$row['id']."\"><input type=\"submit\" value=\"Delete\"></form></td></tr>\n";
		echo "<tr><td>".$row['domain']."<br>$punycode</td><td>".$row['ip']."</td><td align='right'>FTP_USER: ".$row['ftp_user']."<br>DB_USER: ".$row['db_user']."<br> DB_NAME: ".$row['db_name']."<br> DB_PASS: ".$row['db_pass']."<br>FTP_PASS: ".$row['ftp_pass']."<br></td><td><form action=\"?manage=delete\" method=\"post\"><input type=\"hidden\" name=\"id\" value=\"".$row['id']."\"><input type=\"submit\" value=\"Delete\"></form></td></tr>\n";
		}
	echo '</table>';
	mysql_close($mysql_connect);
}


?>
</head>
</html>
